#!/usr/bin/env python

# *************************************************************************

# Copyright 2010 Texas A&M University, 
#                College Station, Texas
#                Contact: R Crosby (rwc@cs.tamu.edu)
#
# Copyright 2003, 2004 by BiRC -- Bioinformatics Research Center
#                University of Aarhus, Denmark
#                Contact: Thomas Mailund <mailund@birc.dk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# *************************************************************************

import ConfigParser
import getopt
import sys
import os
import os.path

# *************************************************************************

def LoadConfig(opt, dflt):

    config = ConfigParser.RawConfigParser()

    if opt.has_key('config'):

        if not os.path.isfile( opt['config'] ):
            print 'Config file', opt['config'], 'not found'
            sys.exit(2)
        else:
            cfile = opt['config']

    elif os.environ.has_key('QQCONFIG'):

        if not os.path.isfile( os.environ['QQCONFIG'] ):
            print 'Config file', opt['config'], 'not found'
            sys.exit(2)
        else:
            cfile = os.environ['QQCONFIG']

    elif os.path.isfile( sys.path[0] + '/' + dflt ):

        cfile = sys.path[0] + '/' + dflt

    else:
        print 'No configuration file found'
        sys.exit(2)

    if opt['verbose']:
        print 'Loading config from', cfile

    try:
        config.read ( cfile )
    except ConfigParser.MissingSectionHeaderError, err:
        print str(err)
        exit(2)
    except ConfigParser.ParsingError, err:
        print str(err)
        exit(2)

    if not opt.has_key('queue'):
        try:
            opt['queue'] = config.get('default','queue')
        except ConfigParser.NoOptionError, err:
            print str(err)
            exit(2)

    if not opt.has_key('batch'):
        try:
            opt['batch'] = config.get('default','batch')
        except ConfigParser.NoOptionError, err:
            print str(err)
            exit(2)

    if not config.has_section(opt['batch']):
        print 'No batch configuration for', opt['batch']
        sys.exit(2)

    return config
    
# *************************************************************************

def ParseCommandLine():
    
    try:
        opts, tfiles = getopt.getopt(sys.argv[1:],
                                   "hvl:x:y:s:c:q:b:",
                                   ["help", "verbose", "tree-limit=", "x=", "y=", "segment-size=", "config=", "queue=", "batch="] )
    except getopt.GetoptError, err:
        print str(err)
        Usage()
        sys.exit(2)

    opt = { 'verbose': False,
            'tlimit' : 0 }


    for key, val in opts:
        if key in ("-v", "--verbose"):
            opt['verbose'] = True
        elif key in ("-h", "--help"):
            Usage()
            sys.exit()
        elif key in ("-l", "--tree-limit"):
            opt['tlimit'] = int(val)
        elif key in ("-s", "--segment-size"):
            opt['segsize'] = int(val)
        elif key in ("-c", "--config"):
            opt['config'] = val
        elif key in ("-q", "--queue"):
            opt['queue'] = val
        elif key in ("-b", "--batch"):
            opt['batch'] = val

    if not opt.has_key('segsize'):
        print 'segment-size option required'
        sys.exit(2)

    if not len(tfiles):
        print 'At least one tree file required'
        sys.exit(2)

    return opt, tfiles

# *************************************************************************

def Usage():
    print '''
pqq - Front end to QuickQuartet for cluster based parallel processing

Usage:

pqq parms treefile(s)

Parms:

   --verbose        (-v) - Be loquacious
   --help           (-h) - Print this message
   --tree-limit=i   (-l) - Process only specified number of trees
   --segment-size=i (-s) - Maximum size of a tree block to process in parallel
   --config=s       (-c) - Name of configuration file (see notes)
   --queue          (-q) - Cluster queue to use
   --batch          (-b) - Batch parameter set to use (from configuration) 

Configuration File:

   The front end requires a configuration file to connect to the cluster
   
   The file is found in the following locations (in precedence order):
   a). The --config parameter
   b). The environment variable QQCONFIG
   c). The file QQFront.cfg in the director containing this script

'''

# *************************************************************************

if __name__ == "__main__":
    opt, tfiles = ParseCommandLine()
    print opt
    print tfiles

    config = LoadConfig(opt)
    print config.sections()
    print 'default', config.options('default')
    print 'cluster', config.options('cluster')
    print 'directories', config.options('directories')
    print 'mail', config.options('mail')
